<template>
  <van-nav-bar title="编辑地址" :fixed="true" left-arrow @click-left="router.back()"/>
  <van-address-edit
    class="mt46"
    :area-list="areaList"
    show-set-default
    show-search-result
    show-delete
    :area-columns-placeholder="['请选择', '请选择', '请选择']"
    area-placeholder="选择省 / 市 / 区"
    :tel-maxlength=11
    :address-info="{
      name:form.name,
      tel:form.phone,
      addressDetail:form.address,
      isDefault:form.is_default,
      province:form.province,
      city:form.city,
      county:form.county,
      areaCode:form.areaCode
    }"
    @save="onSave"
    @delete="onDelete"
    />
</template>
    
<script setup lang='ts'>
// vant提供的中国省市区数据
import { areaList } from '@vant/area-data';
import { useRoute,useRouter } from 'vue-router';
import { addressDetailApi,updateRessListApi,deleteAddress } from '@/api/my'
import { ref,onMounted, reactive } from 'vue';
import { IaddressDetail } from '@/types/my';
import { Toast,Dialog } from 'vant';

  const router = useRouter()
  const route = useRoute()

  let form = ref<any>({})
  const searchResult = ref([]);
  
  let getAddressDetail = async () => {
    let res = await addressDetailApi(Number(route.query.id))
    if(res.status === 200){
      form.value = res.data
      if(form.value.is_default === 0){
        form.value.is_default = false
      }else if(form.value.is_default === 1){
        form.value.is_default = true
      }
      // 找到对应的编码
      let allCode:any = areaList
      for (const key in allCode.county_list) {
        if(form.value.county === allCode.county_list[key]){
          form.value.areaCode = key
        }
      }
    }
  }
  // 点击保存
  let onSave = async (content:IaddressDetail) => {
    if(content.isDefault === true){
      content.isDefault = 1
    }else if(content.isDefault === false){
      content.isDefault = 0
    }
    let list:IaddressDetail = {
      name:content.name,
      address:content.addressDetail,
      phone:content.tel,
      province:content.province,
      city:content.city,
      county:content.county,
      is_default:content.isDefault
    }
    let res = await updateRessListApi(Number(route.query.id),list)
    if(res.status === 204){
      Toast.success("保存成功！")
    }else if(res.status === 422){
      Toast.fail(res.data.errors.phone[0])
    }
    router.back()
  }
  // 点击删除
  let onDelete =  () => {
    Dialog.confirm({
      title: '删除地址信息',
      message: '确定删除吗？',
    })
    .then(async() => {
      let res = await deleteAddress(Number(route.query.id))
      if(res.status === 204){
        Toast.success("删除成功!")
      }else{
        Toast.fail("删除失败!")
      }
      router.back()
    })
    .catch(() => {
        // on cancel
    })
    
  }
  onMounted(() => {
    getAddressDetail()
  })
</script>
    
<style scoped lang="less">
/deep/ .van-button--danger {
    background-color: #1989fa !important;
    border-color: #1989fa;
}
</style>